package TOP101;

/**
 * @Question BM13
 * @Date 2022/11/4 23:57
 * @Solution
 */
public class BM13 {
    //快慢指针 时间复杂度O(N) 空间复杂度O(1)
    public boolean isPail(ListNode head) {
        if (head.next == null) {
            return true;
        }
        //反转链表
        ListNode slow = head;
        ListNode fast = head.next;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        ListNode p = slow.next;
        p = reverse(p);
        //比较
        while (p != null) {
            if (p.val != head.val) {
                return false;
            }
            p = p.next;
            head = head.next;
        }
        return true;
    }

    public static ListNode reverse(ListNode head) {
        ListNode re = null;
        while (head != null) {
            ListNode tem = head.next;
            head.next = re;
            re = head;
            head = tem;
        }
        return re;
    }
}
